package cn.wizzer.app.web.modules.controllers.open;

import cn.hutool.core.lang.UUID;
import cn.wizzer.app.user.modules.models.User;
import cn.wizzer.app.user.modules.models.enums.BizTypeEnum;
import cn.wizzer.app.user.modules.services.UserService;
import cn.wizzer.app.user.modules.services.account.UserAccountRecordService;
import cn.wizzer.framework.util.Id;
import cn.wizzer.framework.util.JSONUtil;
import cn.wizzer.framework.util.Result;
import cn.wizzer.framework.util.debug.Debug;
import com.alibaba.dubbo.config.annotation.Reference;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;

import java.math.BigDecimal;
import java.util.Random;

@IocBean
@At("/open/test")
@Debug
//@Filters({@By(type = ApiTokenFilter.class)})
public class ApiTestController {
    private final static Log log = Logs.get();

    @Inject
    @Reference
    private UserService userService;

    @Inject
    @Reference
    private UserAccountRecordService userAccountRecordService;

    @At
    @Ok("json")
    public void recharge(String appid, String amount, String currencyId) {
        userAccountRecordService.add(currencyId, appid, new BigDecimal(amount), BizTypeEnum.RECHARGE, generateUuid(), "API_TEST" + Id.createOrderNo());
    }

    public String generateUuid() {
        //36位的
        String uuid = UUID.randomUUID().toString();
        String[] strArray = uuid.split("\\s*[-]\\s*");
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < strArray.length; i++) {
            sb.append(strArray[i]);
        }
        uuid = sb.toString();
        return uuid;
    }

    @At
    @Ok("json")
    public void updateUser(String userStr) {
        userService.updateUser(JSONUtil.parseJavaBean(User.class, userStr));
    }

    @At
    @Ok("json")
    public Result randomInviteCode() {
        int i = new Random().nextInt(userService.count());
        return Result.success().addData(userService.query(Cnd.NEW().limit(i, 1)).get(0).getInviteCode());
    }

    @At
    @Ok("json")
    public Result fetchUserByEmail(String email) {
        return Result.success(userService.fetch(Cnd.where("email", "=", email)));
    }

    @At
    @Ok("json")
    public String fetchInviteCodeByPhone(String phone) {
        User user = userService.fetch(Cnd.where("phone", "=", phone));
        if (user == null) {
            return "User(phone=" + phone + ") does not exist";
        }
        return user.getInviteCode();
    }

}
